package com.zhonghe.active4j.function;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

import com.aliyun.oss.common.utils.StringUtils;

public class FunctionTest {

	public String exp = "T(person:[id,name]:[id=9;code=9])";
	
	/**
	 * 利用自定义函数编程计算x + y
	 * @param x 第一个参数值x
	 * @param y 第二个参数值y
	 * @param myFunction 自定义的函数接口
	 * @return x + y
	 */
	public Long getAdd(Long x, Long y, MyFunction<Long, Long> myFunction) {
		return myFunction.handler(x, y);
	}

	@Test
	public void testGetAdd() {
		Long result = getAdd(1L, 2L, (x, y) -> {
			return x + y;
		});
		System.out.println("计算得出的结果为：" + result);
	}
	
	@Test
	public void testGetSql() {
		String formula = "T{person:[sum(amount)]:[id=9;code=9]}";
		List<String> listCompile = new ArrayList<>();
		Matcher matcher = Pattern.compile("^T\\{[\\s\\S]*:\\[[\\s\\S]*\\]:\\[[\\s\\S]*\\]\\}$").matcher(formula);// 用正则匹配
		List<String> data = new ArrayList<>();
		while (matcher.find()) {
			String spiltRules = "T|\\{|\\}|\\:|\\[|\\]";
			String[] array = formula.split(spiltRules);
			for (String s : array) {
				if(StringUtils.isNullOrEmpty(s)) 
				{
					continue;
				}
				data.add(s);
			}
			listCompile.add(matcher.group(0));
		}
		System.out.println(listCompile);
		SqlFunctionService service = new SqlFunctionService();
		String result = service.getSql(data.get(0),data.get(1),data.get(2));
		System.out.println("计算得出的结果为：" + result);
	}
	
	@Test
	public void testGetSql2() {
		List<String> expList = new ArrayList<>();
		List<String> by = new ArrayList<>();
		String formula = "T{person:[sum(amount)]:[id=9;code=9]}-T{person:[sum(amount)]:[id=9;code=9]}+";
		//相减
		Matcher m = Pattern.compile("\\-|\\+|\\/|\\*").matcher(formula);
		while(m.find()) {
			by.add(m.group(0));
		}
		String[] red = formula.split("\\-|\\+|\\/|\\*");
		for(String str :red) {
			Matcher matcher = Pattern.compile("^T\\{[\\s\\S]*:\\[[\\s\\S]*\\]:\\[[\\s\\S]*\\]\\}$").matcher(str);// 用正则匹配
			while (matcher.find()) {
				String spiltRules = "T|\\{|\\}";
				String[] array = str.split(spiltRules);
				for (String s : array) {
					if(StringUtils.isNullOrEmpty(s)) 
					{
						continue;
					}
					expList.add(s);
				}
			}
		}
		SqlFunctionService service = new SqlFunctionService();
		String result = service.getSqlby(expList,by);
		System.out.println("计算得出的结果为：" + result);
		//
		if(Pattern.compile("[\\s\\S]*+[\\s\\S]*").matcher(formula).matches()) {
			
		} 
	}
}
